package com.atguigu.spring.service.impl;

import com.atguigu.spring.dao.api.TigerDao;
import com.atguigu.spring.service.api.TigerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.concurrent.TimeUnit;

@Service
@Transactional(readOnly = true)
public class TigerServiceImpl implements TigerService {

    @Autowired
    private TigerDao tigerDao;

    @Override
    @Transactional(readOnly = false,
            timeout = 3,
            noRollbackFor = FileNotFoundException.class,
            rollbackFor = Exception.class
    )
    public void updateTwice() throws FileNotFoundException {

        // try {TimeUnit.SECONDS.sleep(5);} catch (InterruptedException e) {}

        // 做两次数据库的修改
        Integer tigerId = 5;
        String tigerName = "金渐层2025~~~~~";
        Double tigerSalary = 55555.55;
        tigerDao.updateNameAndSalary01(tigerId, tigerName, tigerSalary);

        new FileInputStream("aaa.txt");

        tigerId = 6;
        tigerName = "银渐层7777~~~~~";
        tigerSalary = 77777.77;
        tigerDao.updateNameAndSalary02(tigerId, tigerName, tigerSalary);
    }

    @Override
    @Transactional(isolation = Isolation.READ_COMMITTED)
    public void getTigerSalaryById() {
        Integer tigerId = 5;
        Double tigerSalary = tigerDao.selectSalaryById(tigerId);
        System.out.println("tigerSalary = " + tigerSalary);
    }

    @Override
    @Transactional(readOnly = false)
    public void updateTigerSalaryById() {
        Integer tigerId = 5;
        Double tigerSalary = 55555d;
        tigerDao.updateTigerSalaryById(tigerId, tigerSalary);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW, readOnly = false)
    public void updateTigerNameById01(Integer tigerId, String tigerName) {
        tigerDao.updateNameById01(tigerId, tigerName);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW, readOnly = false)
    public void updateTigerNameById02(Integer tigerId, String tigerName) {
        tigerDao.updateNameById02(tigerId, tigerName);
    }
}
